package cn.yangliu.springbatch.job;

import cn.yangliu.springbatch.entity.User;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.AfterStep;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.item.database.JpaPagingItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManagerFactory;
import java.util.ArrayList;
import java.util.List;

/**
 * the type of springbatch
 *
 * <p>
 * .
 *
 * @author 杨柳
 * @date 2021-07-12
 */
@Component
public class UserReader extends JpaPagingItemReader<User> {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @PostConstruct
    public void postConstruct() throws Exception {
        //这里选择JPA方式读数据 一个简单的 native SQL
        String jpqlQuery = "FROM User";
        JpaJpqlQueryProvider<User> queryProvider = new JpaJpqlQueryProvider<>();
        queryProvider.setJpqlQuery(jpqlQuery);
        queryProvider.setEntityClass(User.class);
        queryProvider.afterPropertiesSet();
        setTransacted(false);
        setEntityManagerFactory(entityManagerFactory);
        setPageSize(3);
        setQueryProvider(queryProvider);
        //所有ItemReader和ItemWriter实现都会在ExecutionContext提交之前将其当前状态存储在其中,如果不希望这样做,可以设置setSaveState(false)
        setSaveState(true);
    }

    @Override
    public User read() throws Exception {

        User user = super.read();

        if (user!=null && "杨柳".equals(user.getUsername())) {
            stepExecution.getExecutionContext().put("user", user);
        }
        list.add(user);
        return user;
    }

    private List<User> list = new ArrayList<>();

    private StepExecution stepExecution;

    @BeforeStep
    public void beforeStep(StepExecution stepExecution) {
       this.stepExecution = stepExecution;
    }
    @AfterStep
    public void afterStep(StepExecution stepExecution) {
        stepExecution.getJobExecution().getExecutionContext().put("userList", list);
        System.out.println("user reader : " + list);
    }

}
